package com.kele.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kele.service.impl.InsertServiceImpl;

import com.kele.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author kele
 * @date 2021/8/13 11:48
 * @description
 */
@RestController
@RequestMapping("/insert")
public class InsertController {

    private Logger logger= LoggerFactory.getLogger(InsertController.class);

    @Autowired
    private InsertServiceImpl insertService;

    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping("/info")
    public R insertInfo(@RequestBody Object o){
        String exchangeName="direct_insert_exchange";
        String routingKey="user";
        String orderJson = null;
        Message message=null;
        try {
            orderJson = objectMapper.writeValueAsString(o);
            message = MessageBuilder
                    .withBody(orderJson.getBytes())
                    .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                    .build();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        boolean res=insertService.insertInfo(message,exchangeName,routingKey);
        logger.info("o:{}",message);
        if (res){
            return R.ok();
        }
        return R.error(500,"发送失败");

    }
}
